<?php
require_once('wpfunctions.php');
header("Content-type: application/json");
$term = $_REQUEST['term'];
$type = $_REQUEST['type'];
$regex = '/\.gabc$/';
if(!$type) {
  $type='square';
}
if(strrpos($type,'modern')===0) {
  $regex = '/\.json$/';
}

$index = strrpos($term, '/');
if($index === false) {
  $termbeginning = '';
} else {
  $termbeginning = substr($term, 0, $index+1);
}

$result = array();
$dirs = ip_allFiles("engravings/$type/$term");
foreach ($dirs as $i => $dir) {
  $index = strrpos($dir, '/');
  $beginning = substr($dir,$index + 1);
  $dir = substr($dir,0,$index);

  if(is_dir($dir)) {
    $entries = ip_scandir($dir);
    foreach($entries as $v) {
      if(substr($v, 0, strlen($beginning)) == $beginning) {
        if(is_dir("$dir/$v") && !preg_match('/^\.|^\.{1,2}$/',$v)) {
          $result[] = $termbeginning . $v . '/';
        } else if(preg_match($regex,$v)) {
          $result[] = $termbeginning . $v;
        }
      }
    }
  }
}
echo json_encode(array_unique($result));
?>